package br.ufrj.dcc.so;

import java.util.ArrayList;
import java.util.List;

public class MemoriaVirtual {

	List<Frame> frames = new ArrayList<Frame>();

	List<Integer> framesVazios = new ArrayList<Integer>();

	List<Long> historicoThreads = new ArrayList<Long>();

	List<Long> threadsAZerarWS = new ArrayList<Long>();

	public MemoriaVirtual() {
		super();
	}

	public Integer procuraPagina(Pagina p) {
		for (Frame f : frames) {
			if (f.getPagina().equals(p)) {
				return frames.indexOf(f);
			}
		}
		return null;
	}

	public boolean temPagina(Pagina p) {
		for (Frame f : frames) {
			if (f.getPagina().equals(p)) {
				return true;
			}
		}
		return false;
	}

	public void atualizaHistorico(Long idPrograma) {
		synchronized (this) {
			if (historicoThreads.contains(idPrograma)) {
				historicoThreads.remove(idPrograma);
			}
			historicoThreads.add(idPrograma);
			
		}
	}

	public Long removePrograma(List<Long> historico) {
		synchronized (this) {
			Long idARemover = null;
			for (Frame f : frames) {
				if (f.getIdPrograma() == historico.get(0)) {
					// Seta um frame vazio no lugar que estava
					this.getFrames().get(frames.indexOf(f))
							.setIdPrograma(new Long(0));
					this.getFrames().get(frames.indexOf(f))
							.setPagina(new Pagina(0, new Long(0)));
					framesVazios.add(this.getFrames().indexOf(f));
					idARemover = historico.get(0);

				}
			}
			threadsAZerarWS.add(historico.get(0));
			historico.remove(0);
			return idARemover;
		}
	}

	public List<Integer> getFramesVazios() {
		return framesVazios;
	}

	public void setFramesVazios(List<Integer> framesVazios) {
		this.framesVazios = framesVazios;
	}

	public List<Long> getHistoricoThreads() {
		synchronized (this) {
			return historicoThreads;			
		}
	}

	public void setHistoricoThreads(List<Long> historicoThreads) {
		this.historicoThreads = historicoThreads;
	}

	public List<Frame> getFrames() {
		return frames;
	}

	public void setFrames(List<Frame> frames) {
		this.frames = frames;
	}

	public List<Long> getThreadsAZerarWS() {
		return threadsAZerarWS;
	}

	public void setThreadsAZerarWS(List<Long> threadsAZerarWS) {
		this.threadsAZerarWS = threadsAZerarWS;
	}

}
